There are already a bunch of helpful answers on preventing form submit on enter (example1, example2) However none of these work if I want to include the "required" tag on any of the inputs. See code below:
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
// do other stuff
};
return (
<form id="LocationForm" onSubmit={handleSubmit} >
<input type="text" placeholder="Please add country" onKeyUp={handleCountryChange} />
<input type="text" placeholder="Please add city" onKeyUp={handleCityChange} required />
<input type="submit" value="Submit" />
</form>
)
When I press enter in the first input, a dialog pops up that says "This field is required". Ideally, I only want this to pop up when I click the submit button and not when I press enter in any other input. Of course I could implement this logic myself without using the required tags, but would rather avoid re-inventing the wheel here... unless there is some other standard practice that people use. Any pointers?
Try adding onKeyPress={(e) => e.preventDefault() to the <form>